import Vue from 'vue'
import Router from 'vue-router'
import routes from './routers'
import store from '@/store'
import iView from 'iview'
import { canTurnTo, setTitle, setToken } from '@/libs/util'

Vue.use(Router)
const router = new Router({
  routes,
  mode: 'hash'
})

const turnTo = (to, rights, next) => {
  if (canTurnTo(to.name, rights, routes)) next() // 有权限，可访问
  else next({ replace: true, name: '403' }) // 无权限，重定向到403页面
}

router.beforeEach((to, from, next) => {
  iView.LoadingBar.start()
  //如果是首页,且未初始化的
  if(from.path=="/" && !store.state.application.initial){
    let token = to.query.token;
    if(token !== undefined && token !== ''){
      //保存该token
      setToken(token)
    }        
    if(to.name !== '401' ){
      // 初始化
      store.dispatch('initial').then(rights=>turnTo(to, rights, next)).catch((error)=>next({ replace: true, name: '401' }))
    }else{
      next()
    }    
  }else{
    turnTo(to, store.state.application.rights, next)
  }  
})

router.afterEach(to => {
  setTitle(to, router.app)
  iView.LoadingBar.finish()
  window.scrollTo(0, 0)
})

export default router
